import { useState } from 'react';
import { history } from 'umi';
import { Form, Button, Spin, Notification } from '@douyinfe/semi-ui';
import { FormApi } from '@douyinfe/semi-ui/form';
import { useDispatch } from 'react-redux';
import useRequest from '@/hooks/useRequest';
import { login } from '@/services/user';
import { syncAuthState } from '@/store/user';
import { AppDispatch } from '@/store';

interface LoginState {
    account: string;
    email: string;
}

export default function Login() {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const [formAPI, setFormAPI] = useState<FormApi<LoginState>>();
    const dispatch: AppDispatch = useDispatch();

    const { loading, run: loginSubmit } = useRequest(async () => {
        const values = formAPI!.getValues();

        const { status = 1, msg, data } = await login(values);

        dispatch(syncAuthState(data));

        if (status !== 0) {
            Notification.error({
                content: msg || '登录失败，请检查帐号和密码是否正确',
            });
            return;
        }

        Notification.success({
            content: '登录成功，即将跳转到主页',
        });

        history.push('/');
    });

    return (
        <Spin spinning={loading}>
            <Form onSubmit={loginSubmit} getFormApi={api => setFormAPI(api)}>
                <Form.Input
                    label="邮箱"
                    field="email"
                    rules={[{ required: true, message: '请输入你的邮箱' }]}
                    placeholder="请输入邮箱"
                />
                <Form.Input
                    label="密码"
                    type="password"
                    field="password"
                    rules={[{ required: true, message: '请输入你的密码' }]}
                    placeholder="密码"
                />
            </Form>
            <Button
                onClick={() => {
                    formAPI?.submitForm();
                }}
            >
                登录
            </Button>
        </Spin>
    );
}
